package com.dmzc.stage3.Unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/***
 * 修改对象实例的值
 */
public class Test2 {
    public static void main(String[] args) throws Exception {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);
        Guard guard = new Guard();
        System.out.println(guard.giveAccess());
        Field field = guard.getClass().getDeclaredField("ACCESS_ALLOWED");
        unsafe.putInt(guard,unsafe.objectFieldOffset(field),42);
        System.out.println(guard.giveAccess());
    }

    static class Guard {
        private int ACCESS_ALLOWED = 1;

        public boolean giveAccess() {
            return 42 == ACCESS_ALLOWED;
        }
    }
}
